import Promise from '/plugins/es6-promise'

export function showToast({ type, msg, duration }) {
  dd.showToast({
    type: type || 'fail',
    content: msg,
    duration: duration || 1500
  });
}

export function getLocation() {
  return new Promise((resolve, reject) => {
    dd.getLocation({
      success(res) {
        if (res.address) {
          resolve(res)
        } else {
          dd.httpRequest({
            url: "https://restapi.amap.com/v3/geocode/regeo",
            method: "get",
            dataType: "json",
            data: {
              key: "44c28d1726ce4eac2a58bf21889f616d",
              location: res.longitude + "," + res.latitude
            },
            success: (result) => {
              if (result.status === 200 && result.data && result.data.info === "OK") {
                res.address = result.data.regeocode.formatted_address
              }
              resolve(res)
            },
            fail: (err) => {
              resolve(res)
            }
          })
        }
      },
      fail(err) {
        reject(err)
        dd.alert({ title: "定位失败，请确认网络是否正常、定位权限是否开启" })
        // if (err.error === 11) {
        //   dd.alert({ title: '请确认定位相关权限已开启' });
        // } else if (err.error === 12) {
        //   dd.alert({ title: '网络异常，请稍后再试' });
        // } else if (err.error === 13) {
        //   dd.alert({ title: '定位失败' });
        // } else if (err.error === 14) {
        //   dd.alert({ title: '业务定位超时' })
        // }
      },
    })
  })
}

export function chooseImage({ count = 1, sourceType = ['camera', 'album'] }) {
  return new Promise((resolve, reject) => {
    dd.chooseImage({
      count: count,
      sourceType: sourceType,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    });
  })
}

export function uploadFile({
  url: files,
  type
}) {
  return new Promise(async (resolve, reject) => {
    dd.showLoading({
      content: "加载中..."
    });
    let result = [];
    for (let i = 0; i < files.length; i++) {
      let file = await upload({
        url: files[i], type
      });
      result.push(file);
    }
    dd.hideLoading();
    resolve(result);
  })
}

export function upload({ url, type, compressFlag = false }) {
  return new Promise((resolve, reject) => {
    const app = getApp();
    dd.uploadFile({
      url: app.globalData.uploadUrl,
      formData: { watermarkFlag: false, compressFlag: compressFlag },
      fileType: type,
      fileName: 'file',
      filePath: url,
      success: (res) => {
        let response = JSON.parse(res.data);
        if (response.success) {
          resolve(response.vo);
        } else {
          dd.hideLoading();
          showToast({
            msg: response.message[0]
          });
          reject(new Error(response.message[0]))
        }
      },
      fail: (err) => {
        dd.hideLoading();
        showToast({
          msg: "上传失败" + JSON.stringify(err)
        });
        reject(err);
      }
    });
  })
}

export function onPlayRecord(url) {
  return new Promise((resolve, reject) => {
    const app = getApp()
    if (app.globalData.systemInfo.platform === 'iOS') {
      dd.downloadFile({
        url: url,
        success({ filePath }) {
          let bam = dd.getBackgroundAudioManager();//背景音频管理器
          //监听背景音频错误事件, 错误类型（10001-系统错误 10002-网络错误 10003-文件错误 10004-格式错误）
          bam.onError = (err) => {
            showToast({ msg: JSON.stringify(err) });
            reject(err)
          }
          bam.onEnded = () => {
            resolve()
          }
          bam.src = filePath;
          bam.title = '';//不实例化此属性，ios调用多次play()，playbackRate会累加
          bam.play();
        },
        fail(res) {
          dd.alert({
            content: res.errorMessage || res.error,
          });
        },
      });
    } else {
      let bam = dd.getBackgroundAudioManager();//背景音频管理器
      //监听背景音频错误事件, 错误类型（10001-系统错误 10002-网络错误 10003-文件错误 10004-格式错误）
      bam.onError = (err) => {
        showToast({ msg: JSON.stringify(err) });
        reject(err)
      }
      bam.onEnded = () => {
        resolve()
      }
      bam.src = url;
      bam.title = '';//不实例化此属性，ios调用多次play()，playbackRate会累加
      bam.play();
    }
  })
}

